import json, os
from uuid import uuid4
from django.db.models import F, Q
from ..tools.token import AuthJWT
from .base import BaseView
from kg_back.settings import BASE_DIR
from django.http.request import HttpRequest
from api.tools.generate import get_graph_data
from ..models.user_serializer import UserInfoSerializer


# Create your views here.
class GraphBaseView(BaseView):
    DATASET_PATH = BASE_DIR.joinpath('api', 'dataset', 'graph.json')


class GraphAllView(GraphBaseView):
    ''' 所有的知识图谱 '''
    def get(self, request: HttpRequest):
        with open(self.DATASET_PATH, 'r') as fp:
            data = json.load(fp)
        return self.to_json(data=data)

class GraphSearchView(GraphBaseView):
    ''' 搜索知识图谱 '''
    def get(self, request: HttpRequest):
        with open(self.DATASET_PATH, 'r') as fp:
            data = json.load(fp)
        key = request.GET.get('key')
        nodes = filter(lambda node: key in node['name'], data['nodes'])
        data['nodes'] = list(nodes)
        return self.to_json(data=data)

class GraphGenerateView(GraphBaseView):
    ''' 生成知识图谱 '''
    def post(self, request: HttpRequest):
        doc = request.POST.get('doc')
        if not doc:
            doc = json.loads(request.body).get('doc')
        if not doc:
            return self.resp_err(message='请输入需要生成知识图谱的文本')
        data = get_graph_data(doc)
        return self.to_json(data=data)


